package com.ruoyi.tb.lmt.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.GuidUtil;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.tb.lmt.domain.bo.TbMessageNoticeBo;
import com.ruoyi.tb.lmt.domain.vo.TbMessageNoticeVo;
import com.ruoyi.tb.lmt.service.ITbLmtrepairWorkdetailService;
import com.ruoyi.tb.lmt.service.ITbMessageNoticeService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbRequestVo;
import com.ruoyi.tb.lmt.domain.bo.TbRequestBo;
import com.ruoyi.tb.lmt.service.ITbRequestService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 事件申请
 *
 * @author ruoyi
 * @date 2024-01-18
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/request")
public class TbRequestController extends BaseController {

    private final ITbRequestService iTbRequestService;

    @Autowired
    private ITbMessageNoticeService iTbMessageNoticeService;

    @Autowired
    private ITbLmtrepairWorkdetailService iTbLmtrepairWorkdetailService;

    @Autowired
    private ISysRoleService iSysRoleService;

    /**
     * 查询事件申请列表
     */
    @GetMapping("/list")
    public TableDataInfo<TbRequestVo> list(TbRequestBo bo, PageQuery pageQuery) {
        return iTbRequestService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出事件申请列表
     */
    @Log(title = "事件申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbRequestBo bo, HttpServletResponse response) {
        List<TbRequestVo> list = iTbRequestService.queryList(bo);
        ExcelUtil.exportExcel(list, "事件申请", TbRequestVo.class, response);
    }

    /**
     * 获取事件申请详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("xha-lmt:request:query")
    @GetMapping("/{id}")
    public R<TbRequestVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iTbRequestService.queryById(id));
    }

    /**
     * 新增事件申请
     */
    @SaCheckPermission("xha-lmt:request:add")
    @Log(title = "事件申请", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbRequestBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long workGroupId = loginUser.getDeptId();
        String workUser = loginUser.getUsername();
        String workGroup = loginUser.getDeptName();
        Long requireId = GuidUtil.getZcbhid();
        bo.setId(requireId);
        bo.setWorkGroupId(workGroupId);
        bo.setWorkGroup(workGroup);
        bo.setWorkUser(workUser);
        bo.setWorkTime(new Date());
        bo.setStatus("审批中");
        bo.setCreateBy(workUser);
        bo.setCreateTime(new Date());
        bo.setRequestNeed(iTbMessageNoticeService.getInspection());
        //添加到消息通知
        TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
        messageNoticeBo.setLmtType(bo.getLmtType());
        messageNoticeBo.setLmtNumber(bo.getLmtNumber());
        messageNoticeBo.setWorkGroupId(workGroupId);
        messageNoticeBo.setWorkGroup(workGroup);
        messageNoticeBo.setWorkerTeam(bo.getWorkerTeam());
        messageNoticeBo.setWorkUser(workUser);
        messageNoticeBo.setWorkTime(new Date());
        messageNoticeBo.setMessageTitle(bo.getRequestType()+"申请");
        messageNoticeBo.setMessageName(workGroup+"提交了"+bo.getLmtNumber()+"大机的"+bo.getRequestType()+"申请,请查看。");
        messageNoticeBo.setStatus("0");
        messageNoticeBo.setMessageType("事件申请");
        messageNoticeBo.setCreateBy(workUser);
        messageNoticeBo.setCreateTime(new Date());
        messageNoticeBo.setTaskUrl(bo.getTaskUrl());
        messageNoticeBo.setMessageNeed(bo.getRequestName());
        messageNoticeBo.setMessageId(requireId);

        //设置消息接收人为巡检组
        messageNoticeBo.setRecipient(iTbMessageNoticeService.getInspection());
        iTbMessageNoticeService.insertByBo(messageNoticeBo);
        return toAjax(iTbRequestService.insertByBo(bo));
    }

    /**
     * 修改事件申请
     */
    @SaCheckPermission("xha-lmt:request:edit")
    @Log(title = "事件申请", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbRequestBo bo) {
        return toAjax(iTbRequestService.updateByBo(bo));
    }

    /**
     * 删除事件申请
     *
     * @param ids 主键串
     */
    @SaCheckPermission("xha-lmt:request:remove")
    @Log(title = "事件申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTbRequestService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    //查询事件申请
    @SaCheckPermission("xha-lmt:request:selectRequestList")
    @GetMapping("/query")
    public TableDataInfo<TbRequestVo> selectRequestList(String requestType, String workerTeam,String lmtType,String lmtNumber,String workGroup,String startTime,String endTime, PageQuery pageQuery) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = null;
        Date end = null;
        if (startTime != null || endTime != null) {
            start = formatter.parse(startTime);
            end = formatter.parse(endTime);
        }
        return iTbRequestService.selectRequestList(requestType, workerTeam,lmtType,lmtNumber,workGroup,start,end,pageQuery);
    }

    //通过事件申请
    @SaCheckPermission("xha-lmt:request:accept")
    @Log(title = "事件申请", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/accept")
    public R<Void> accept(@Validated(EditGroup.class) @RequestBody TbRequestBo bo) {
        String username = LoginHelper.getLoginUser().getUsername();
        if (!isUserInspection(username) && !isAdmin(username)) {
            throw new IllegalArgumentException("您没有权限审批该申请");
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long workGroupId = loginUser.getDeptId();
        String workUser = loginUser.getUsername();
        String workGroup = loginUser.getDeptName();

        bo.setStatus("已通过");
        bo.setRequestNeed(workUser);

        TbMessageNoticeVo tbMessageNoticeVo = iTbMessageNoticeService.selectById(bo.getId());

        //添加到消息通知
        TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
        messageNoticeBo.setLmtType(bo.getLmtType());
        messageNoticeBo.setLmtNumber(bo.getLmtNumber());
        messageNoticeBo.setWorkGroupId(workGroupId);
        messageNoticeBo.setWorkGroup(workGroup);
        messageNoticeBo.setWorkerTeam(bo.getWorkerTeam());
        messageNoticeBo.setWorkUser(workUser);
        messageNoticeBo.setWorkTime(new Date());
        messageNoticeBo.setMessageTitle(bo.getRequestType()+"申请");
        messageNoticeBo.setMessageName(workUser+"通过了"+bo.getLmtNumber()+"大机的"+bo.getRequestType()+"申请,请查看。");
        messageNoticeBo.setStatus("0");
        messageNoticeBo.setMessageType("事件申请");
        messageNoticeBo.setCreateBy(workUser);
        messageNoticeBo.setCreateTime(new Date());
        messageNoticeBo.setTaskUrl(bo.getTaskUrl());
        messageNoticeBo.setMessageNeed(bo.getRequestName());
        messageNoticeBo.setMessageId(bo.getId());

        //设置消息接收人为申请人
        messageNoticeBo.setRecipient(tbMessageNoticeVo.getCreateBy());
        iTbMessageNoticeService.insertByBo(messageNoticeBo);

        return toAjax(iTbRequestService.updateByBo(bo));
    }

    public boolean isUserInspection(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有巡检组的角色标识
        for (SysRole role : userRoles) {
            if ("spection".equals(role.getRoleKey())) {
                    return true;
                }
            }
            return false;
        }

        @SaCheckPermission("xha-lmt:request:reject")
    @Log(title = "拒绝事件申请", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/reject")
    public R<Void> reject(@Validated(EditGroup.class) @RequestBody TbRequestBo bo) {
        String username = LoginHelper.getLoginUser().getUsername();
        if (!isUserInspection(username) && !isAdmin(username)) {
            throw new IllegalArgumentException("您没有权限审批该申请");
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long workGroupId = loginUser.getDeptId();
        String workUser = loginUser.getUsername();
        String workGroup = loginUser.getDeptName();

        bo.setStatus("已驳回");
        bo.setRequestNeed(workUser);

        TbMessageNoticeVo tbMessageNoticeVo = iTbMessageNoticeService.selectById(bo.getId());
        //添加到消息通知
        TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
        messageNoticeBo.setLmtType(bo.getLmtType());
        messageNoticeBo.setLmtNumber(bo.getLmtNumber());
        messageNoticeBo.setWorkGroupId(workGroupId);
        messageNoticeBo.setWorkGroup(workGroup);
        messageNoticeBo.setWorkerTeam(bo.getWorkerTeam());
        messageNoticeBo.setWorkUser(workUser);
        messageNoticeBo.setWorkTime(new Date());
        messageNoticeBo.setMessageTitle(bo.getRequestType()+"申请");
        messageNoticeBo.setMessageName(workUser+"驳回了"+bo.getLmtNumber()+"大机的"+bo.getRequestType()+"申请,请查看。");
        messageNoticeBo.setStatus("0");
        messageNoticeBo.setMessageType("事件申请");
        messageNoticeBo.setCreateBy(workUser);
        messageNoticeBo.setCreateTime(new Date());
        messageNoticeBo.setTaskUrl(bo.getTaskUrl());
        messageNoticeBo.setMessageNeed(bo.getRequestName());
        messageNoticeBo.setMessageId(bo.getId());

        //设置消息接收人为申请人
        messageNoticeBo.setRecipient(tbMessageNoticeVo.getCreateBy());
        iTbMessageNoticeService.insertByBo(messageNoticeBo);

        return toAjax(iTbRequestService.updateByBo(bo));

    }

    public boolean isAdmin(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有管理员角色
        for (SysRole role : userRoles) {
            if ("admin".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }
}
